package com.hichina.client;


import com.hichina.client.util.HttpClientUtils;
import com.hichina.client.util.PageList;
import com.hichina.client.util.ResponseUtils;
import com.hichina.client.util.Setting;
import com.hichina.exception.HiChinaException;
import com.hichina.exception.InvalidTokenException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import javax.security.auth.login.AccountException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: zigang.wang
 * Date: 12-2-28
 * Time: 下午6:21
 * To change this template use File | Settings | File Templates.
 */
public class HiChina {
    public static final Logger log = Logger.getLogger(HiChina.class);
    private HttpClientUtils httpClient ;
    public static final String apiServer = "http://api.hichinacloud.com";

    /**
     * 
     * @param redirectUri
     * @param clientId
     * @param clientSecret
     */
    public HiChina(String redirectUri, String clientId, String clientSecret) {
        httpClient = new HttpClientUtils("", redirectUri, clientId, clientSecret, apiServer);
    }

    public HiChina(){
        httpClient = new HttpClientUtils();
    }

    
    public void setApiServer(String apiServer){
        this.httpClient.setApiServer(apiServer);
    }


    public void setAccessToken(String accessToken){
        httpClient.setAccessToken(accessToken);
    }

    public  String getAuthorizeUrl() {
        return httpClient.getApiServer() + "/oauth/authorize?" + "response_type=code&client_id=" + httpClient.client_id + "&redirect_uri=" + httpClient.redirectURI ;
    }

    /**
     * 获取token
     * @param code
     * @return
     * @throws HiChinaException
     * @throws InvalidTokenException
     */
    public Token getAccessToken(String code) throws HiChinaException, InvalidTokenException {
        try {
            return new Token(httpClient.getAccessToken(code));
        } catch (JSONException e) {
            log.error("JSONError:", e);
            throw new HiChinaException( "can not conver to JSONObject");
        }
    }

   /* *//**
     * 刷新token
     * @param refreshToken
     * @return
     * @throws HiChinaException
     * @throws InvalidTokenException
     *//*
    public Token refreshAccessToken(String refreshToken) throws HiChinaException, InvalidTokenException {
        try {
            return new Token(httpClient.refreshAccessToken(refreshToken));
        } catch (JSONException e) {
            log.error("JSONError:", e);
            throw new HiChinaException(" can not conver to JSONObject");
        }
    }*/

    /**
     * 获取当前用户账号
     * @return
     * @throws InvalidTokenException
     * @throws HiChinaException
     */
    public String getUid() throws InvalidTokenException, HiChinaException {
        try {
            JSONObject json = ResponseUtils.checkResponse(httpClient.getUid());
            return json.getString("uid");
        } catch (JSONException e) {
            throw new HiChinaException(" can not conver to JSONObject");
        }
    }

    /**
     * 获取当前用户详情
     * @param uid
     * @return
     * @throws HiChinaException
     * @throws InvalidTokenException
     */
    public Account getAccountDetail( String uid) throws HiChinaException, InvalidTokenException {
            return new Account(httpClient.getAccountInfo(uid));
    }



    /**
     * 获取域信息
     * @param uid
     * @return
     * @throws InvalidTokenException
     * @throws HiChinaException
     */
    public DomainInfo getDomainInfo(String uid) throws InvalidTokenException,  HiChinaException {
        return new DomainInfo(httpClient.getDomainInfo(uid));
    }

    /**
     * 获取用户状态， 0：已购买，1：试用  ， 2： 开发者测试
     * @param uid
     * @return
     * @throws InvalidTokenException
     * @throws HiChinaException
     */
    public String getAccountStatus(String uid) throws InvalidTokenException, HiChinaException {
        try {
            JSONObject json = ResponseUtils.checkResponse(httpClient.getAccountStatus(uid));
            return json.getString("status");
        } catch (JSONException e) {
            throw new HiChinaException(" can not conver to JSONObject");
        }
    }

    //------------------需要开通权限的接口---------------------
    /**
     * 由 uid 获得mail，需要有获取mail的权限
      * @param uid
     * @return
     * @throws InvalidTokenException
     * @throws HiChinaException
     * @throws JSONException
     */
    public String getMail(String uid) throws InvalidTokenException, HiChinaException, JSONException {
        JSONObject json = ResponseUtils.checkResponse(httpClient.getMail(uid));
        return json.getJSONObject("data").getString("mail");
    }

    /**
     * 获得联系人列表
     * @param uid
     * @return
     * @throws InvalidTokenException
     * @throws IOException
     * @throws HiChinaException
     */
    public AccountList listContactAccount(String uid, int offset, int length) throws InvalidTokenException,  HiChinaException {
        return new AccountList(httpClient.getContactList(uid, offset, length));
    }

    /**
     * 获取当前用户域下所有可以使用当前应用的用户
     * @param uid
     * @return
     * @throws InvalidTokenException
     * @throws HiChinaException
     */
    public AccountList listValidAccount(String uid) throws InvalidTokenException,  HiChinaException {
        return new AccountList(httpClient.getValidList(uid));
    }

    /**
     * 获取当前用户公司的所有部门列表，
     * @param domain 域
     * @return
     * @throws InvalidTokenException
     * @throws HiChinaException
     */
    public List<Department> listDepartment(String domain) throws InvalidTokenException, HiChinaException {
         JSONObject json = ResponseUtils.checkResponse(httpClient.listDepartment(domain));
        List<Department> departmentList = null;
        try {
            JSONObject data = json.getJSONObject("data");
            String departmentStr = data.getString("departments");
            JSONArray departments = new JSONArray(departmentStr);
            departmentList = new ArrayList<Department>();
           for(int i = 0; i < departments.length(); i++){
                departmentList.add(new Department((JSONObject) departments.get(i)));
           }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return departmentList;
    }


    /**
     * 获取当前公司部门内的员工列表
     * @param domain
     * @param departmentId
     * @param offset
     * @param length
     * @return
     * @throws InvalidTokenException
     * @throws HiChinaException
     * @throws JSONException
     */
    public PageList<Account> listDepartmentAccount(String domain, String departmentId,int offset, int length) throws InvalidTokenException, HiChinaException, JSONException {
        JSONObject json = ResponseUtils.checkResponse(httpClient.listDepartmentAccount(domain, departmentId, offset, length));
        List<Account> accountList = new ArrayList<Account>();
        JSONArray accounts = json.getJSONArray("accounts");
//        JSONArray accounts = new JSONArray(json.getString("accounts"));
        for(int i = 0; i<accounts.length(); i++){
            accountList.add(new Account((JSONObject) accounts.get(i)));
        }
        PageList<Account> pageList = new PageList<Account>();
        pageList.setLength(length);
        pageList.setOffset(offset);
        pageList.setTotalSize(json.getLong("total"));
        pageList.setElements(accountList);
        return pageList;
    }

    public JSONObject listAccounts(String domain, int offset, int length, long fecthtime) throws InvalidTokenException, HiChinaException {
        JSONObject json = ResponseUtils.checkResponse(httpClient.listAccounts(domain, offset, length, fecthtime));
        return json;
    }


}
